package servlet.assitant;

import dao.domain.Book;
import service.BookService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author gzb
 * @Date 2023/10/17
 * @Description ${PACKAGE_name}
 */
@WebServlet(name = "BookAddServlet", value = "/BookAddServlet")
public class AddBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 2023/9/20 修改书籍信息
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        String publisher = request.getParameter("publisher");
        String priceStr = request.getParameter("price");
        double price = (priceStr == null || priceStr.isEmpty()) ? 10000 : Double.parseDouble(priceStr);
        String quantityStr = request.getParameter("quantity");
        int quantity = (quantityStr == null || quantityStr.isEmpty()) ? 1 : Integer.parseInt(quantityStr);
        Book book = new Book(1, name, author, publisher, price, quantity);
        String msg;
        try {
            BookService.save(book);
            msg = "{\"msg\":\"success\"}";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write(msg);
        System.out.println("finish");
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("BookAddServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
